<template>
  <div class="subject-right">
    <div class="subject-right-header">
      <div class="resourceTop">
        <div class="text">
          <p class="title007">班级管理</p>
          <p>
            <span>&nbsp;{{zhuanye}}&nbsp;专业教研负责人</span>
          </p>
        </div>
        
        <div class="button-zuzhang">
          <el-button size="large" 
            round 
            @click="HandClickcreateClass" 
            color="#ff5f57" 
            style="color: #fff">
            创建班级
          </el-button>
        </div>
      </div>
    </div>

    <div class="subject-right-body">
      <div class="table">
        <el-table 
          v-loading="loading"
          :data="tableDatas" 
          height="74vh" 
          style="width: 100%" 
          empty-text="当前没有班级" 
          @row-click="acs"
          :row-style="{ height: '80px' }">
          <el-table-column prop="classId" label="班级编号" align="center" />
          <el-table-column prop="className" label="班级名" align="center" sortable />
          <el-table-column  label="方向" align="center" sortable>
            {{ zhuanye }}
          </el-table-column>
          <el-table-column prop="classTeacher" label="班级老师" align="center" sortable>
            <template #default="scope">
            {{ scope.row.classTeacher && scope.row.classTeacher.length > 0 ? scope.row.classTeacher.map(teacher => teacher.nickName).join(', ') : '未分配' }}
          </template>
          </el-table-column>
          <el-table-column prop="id" label="管理" align="center">
            <template #default="scope">
              <div style="display: flex; gap: 20px;">
                <el-button size="small" round 
                @click="toggleDialog(scope.row)" 
                color="#ff5f57" 
                style="color: #fff">
                  分配老师
                </el-button>
                <!-- <el-button 
                  size="small" 
                  round 
                  @click="viewclasss(scope.row)" 
                  color="#ff5f57" style="color: #fff">
                  查看班级
                </el-button> -->
                <el-button size="small" round @click="editClass(scope.row)" color="#ff5f57" style="color: #fff">
                  编辑
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

      <!-- 分配老师弹出框 -->
  <el-dialog v-model="dialogVisible" title="分配老师" width="30%">
    <el-form label-width="110px" label-position="left">
      <el-form-item label="班级 :">
        <el-input v-model="rowclass.className" disabled></el-input>
      </el-form-item>
      <el-form-item label="现有老师 :">
        <p v-if="rowclass.classTeacher && rowclass.classTeacher.length > 0">
          {{ rowclass.classTeacher.map(teacher => teacher.nickName).join(', ') }}
        </p>
        <p v-else>未分配</p>
      </el-form-item>
      <el-form-item label="分配老师 :">
        <el-select 
          v-model="labelsString" 
          multiple 
          placeholder="选择老师" 
          @change="handleChange">
            <el-option
            v-for="item in leaders"
            :key="item.labelId"
            :label="item.nickName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="assignTeacher" style="width:15%;">确定</el-button>
        <el-button @click="dialogVisible = false" style="width:15%;">取消</el-button>
      </span>
    </template>
  </el-dialog>

    <!-- 创建班级弹出框 -->
    <el-dialog v-model="createclass" title="创建班级" width="20%">
      <el-form label-width="70px" v-model="createOneClass" label-position="left" >
        <el-form-item label="班级名 :">
          <el-input v-model="createOneClass.className" placeholder="请输入班级名"></el-input>
        </el-form-item>
        <el-form-item label="方向 :">
          <el-input  disabled v-model="zhuanye "></el-input>
        </el-form-item>
        <!-- <el-form-item label="学校 :">
          <el-input  disabled v-model="schoolList "></el-input> -->
        <!-- </el-select> -->
      <!-- </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handleCreateClass" style="width:15%;">确定</el-button>
          <el-button @click="createclass = false" style="width:15%;">取 消 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑班级弹出框 -->
    <el-dialog v-model="lookclass" title="编辑班级" width="20%">
      <el-form label-width="70px"  :model="watchClass" label-position="left" >
        <el-form-item label="班级名 :">
          <el-input v-model="watchClass.className" placeholder="请输入班级名"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="handlechangeClass" style="width:15%;">确定</el-button>
          <el-button @click="handQuxiao(res)" style="width:15%;">取 消 </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配班级确认信息弹出框 -->
    <el-dialog v-model="banjiquer" title="分配老师确认 " width="30%">
      <p style="font-size: 17px; color: brown;">
        您即将对 &nbsp;&nbsp;{{ rowclass.className}}&nbsp;&nbsp;班的老师进行分配
      </p>
      
      <el-form label-width="200px" label-position="left" >
        <el-form-item label="目前正在管理中的老师 :">
          <p style="margin-top: 19px;" v-if="rowclass.classTeacher && rowclass.classTeacher.length > 0">
            {{ rowclass.classTeacher.map(teacher => teacher.nickName).join(', ') }}
          </p>
          <p v-else style="margin-top: 19px;">未分配</p>
        </el-form-item>
        <el-form-item label="修改后的管理老师 :">
          <p style="margin-top: 19px;" v-if="newteacher != ''">
           {{ rowclass.newteacher }}
          </p>
          <p v-else style="margin-top: 19px;">未选择</p>
        </el-form-item>  
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button 
            type="primary" 
            @click="fenpeiqq" 
            style="width:15%;">
            分配确认
          </el-button>
          <!-- <el-button @click="createclass = false" style="width:15%;">分配取消</el-button> -->
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref,onMounted } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { dataType } from "element-plus/es/components/table-v2/src/common";
import router from "@/router";
import { ElMessage, ElMessageBox } from "element-plus";
import {selectAllByMajorId,selectTeacherMessage,fenpeiTeacher,addOneClass,changeOneClass} from '@/api/TeacheringResearch/teacherResearch.js'
import { selectAllSchool,selectSubjectLabelById } from "@/api/teacher/AddClass"
import { reactive } from 'vue'
import {
  ArrowLeft,
  ArrowRight,
  Delete,
  Edit,
  Share,
  Search,
} from "@element-plus/icons-vue";
import {
  insterClass,
  findClassroomByTeacherId,
  deleteClass,
  updateClass,
  findClassroomByClassId,
} from "@/api/teacher/AddClass";
import { useUserInfoStore } from "@/store/user.js";

const loading = ref(false)

//创建班级传参数据模型
const createOneClass = ref({})



//发送给后端分配的老师Id
const updateTeacherId = ref([])

const handleChange = (e) => { // e 为选中的老师的 ID 集合
   (e);

  updateTeacherId.value = e;

  // 遍历 e 集合，与 leaders 集合中的 userId 进行比较
  const selectedNicknames = e.map(id => {
    const leader = leaders.value.find(leader => leader.userId === id);
    return leader ? leader.nickName : null;
  }).filter(nickName => nickName !== null);

  // 使用逗号拼接并存放在一个变量中
  const selectedNicknamesString = selectedNicknames.join(', ');


  rowclass.value.newteacher = selectedNicknamesString;
  selectedLeader.value = e;//下拉框默认显示
}

//后端请求数据模型
const forms = ref({})

// 分配老师二次确认按钮事件
const fenpeiqq = ()=> {
  //从token中获取专业
  const mid = useUserInfoStore().userInfo.majorId
  //存入后端请求数据模型
  forms.value.teachersId = updateTeacherId.value;
  forms.value.majorId = mid
  forms.value.classId = rowclass.value.classId

  // 调用后端接口
  fenpeiTeachers();

}

//向后端发送请求数据
const fenpeiTeachers = async () => {
  const res = await fenpeiTeacher(forms.value);
  ElMessage.success(res.data);
 
  //关闭所有的弹窗
  banjiquer.value = false;
  dialogVisible.value = false;
  //重新查询
  ALLMarjor()
}

onMounted(() => {
  ALLMarjor()
  selectMajor()
})

//专业负责人所属信息
const zhuanye =  ref()
//根据专业id查询专业的名称
const selectMajor =async ()=>{
  const mid = useUserInfoStore().userInfo.majorId
 let ss=await selectSubjectLabelById(mid)

 zhuanye.value=ss.data.directionName
}

const labelsString = ref([]);

//现有老师数据模型
const existingTeachers = ref('');


// 新增数据属性
const selectedClassName = ref('');

//单行班级信息模型
const rowclass = ref({});

// 控制分配老师弹出框
const dialogVisible = ref(false);

//控制查看班级信息弹出框
const lookclass = ref(false);

//控制分配班级确认弹出框
const banjiquer = ref(false);


const viewclasss = (res)=>{
  lookclass.value = true;
}


// 根据id查询所有的专业
const ALLMarjor = async () => {
  loading.value = true;
  const mid = useUserInfoStore().userInfo.majorId
  const res = await selectAllByMajorId(mid);//专业id暂时写死

  tableDatas.value = res.data;
  loading.value = false;

};

// 分配老师弹出框确认按钮
const assignTeacher = () => {

  //打开确认分配班级确认弹出框
  banjiquer.value = true;


  // 清空输入框
  // selectedClassName.value = '';
  // selectedLeader.value = [];

  // // 关闭对话框
  // dialogVisible.value = false;


  // // 显示成功消息
  // ElMessage({
  //   type: "success",
  //   message: "老师分配成功",
  // });

};



// 分配老师弹出框点击按钮
const toggleDialog = (res) => {


  // 清空已选老师
  updateTeacherId.value = [];
  //清除老师名字
  rowclass.value.newteacher = '';

  rowclass.value = res; // 赋值给班级行对象

  dialogVisible.value = !dialogVisible.value;
  const aa = res.classTeacher;

  // 遍历 aa 数组，提取 userId 并放入 labelsString 数组中
  labelsString.value = aa.map(item => item.userId);
  //调用下拉框获取老师信息
  xialateachermeaasge();
};

//学校下拉框数据模型
const schoolList = ref('');
schoolList.value = "华信智原";
//控制创建班级弹出框
const createclass = ref(false);

// 创建班级点击按钮
const HandClickcreateClass = () => {
  // 清空数据
  createOneClass.value = {}

  createclass.value = true;

  // findSchool()//调用查询学校接口
  
}

//发送后端请求学校数据
// const findSchool= async ()=>{
//   const res = await selectAllSchool();

//   schoolList.value = res.data;
// }


// 创建班级确认方法
const handleCreateClass = async () => {
    // 判空处理
    if (!createOneClass.value.className) {
    ElMessage({
      type: "error",
      message: "班级名不能为空",
    });
    return; // 阻止后续操作
  }
  const mid = useUserInfoStore().userInfo.majorId
  createOneClass.value.marjorId = mid//暂时写死,之后从登录中的pinia获取老师的专业id
  createOneClass.value.schoolId = 1;
  try {
    const res =  await addOneClass(createOneClass.value);
    // 显示成功消息
    ElMessage({
      type: "success",
      message: "班级创建成功",
    });
    createclass.value = false;
    //刷新班级列表或其他操作
    ALLMarjor();
  } catch (error) {
    // 处理错误
    ElMessage({
      type: "error",
      message: res.data.message,
    });
  }
};





//编辑班级弹框数据模型
const watchClass = ref({});

// 编辑班级方法
const editClass = (row) => {
  // 这里可以添加编辑班级的具体逻辑
  lookclass.value = true;//开启弹窗框

  watchClass.value.classId = row.classId;//行对象赋值个表单
  watchClass.value.className = row.className;//行对象赋值个表单

};
//编辑确认事件
const handlechangeClass = () =>{
  updateclass();
}

//发请求修改班级
const updateclass = async () => {
  try {
    const res = await changeOneClass(watchClass.value);

    // 关闭创建班级弹窗
    lookclass.value = false;
    // 显示成功消息
    ElMessage({
      type: "success",
      message: "班级修改成功",
    });
    ALLMarjor();

  }catch (error) {
    // 处理错误
    ElMessage({
      type: "error",
      message: res.data.message,
    });

  }

}

//编辑取消事件
const handQuxiao = (res)=> {
  ALLMarjor()
  lookclass.value = false;//关闭弹窗框
}


const leaders = ref([]);
// 下拉框获取老师信息
const xialateachermeaasge = async () => {
  const mid = useUserInfoStore().userInfo.majorId
  let res = await selectTeacherMessage(mid);
  // 获取当前点击行对象
  leaders.value = res.data;
};
// 下拉框选项数据


// 分配老师下拉框选择值
const selectedLeader = ref([]); // 确保这是一个数组


const handleClose = () => {
  dialogVisible.value = true;
};


// 当前操作的id
const classId = ref();
// 操作锁
const lock = ref("跳转");

const acs = (row) => {
  classId.value = row.id;
  if (lock.value == "跳转") {
    // alert("跳转页面=" + classId.value)
  }
  if (lock.value == "修改") {
    update(row.studentNum, classId.value);
  }
  if (lock.value == "删除") {
    if (row.courseNum > 0 || row.studentNum > 0) {
      ElMessageBox.alert("该标签下有题目,若强行删除会导致题目丢失", "提示", {
        confirmButtonText: "确定",
        type: "warning",
      });
    } else {
      // 删除逻辑
    }
  }
  lock.value = "跳转";
};

// 班级列表模型
const tableDatas = ref([]);

// 添加专业
const open = () => {
  ElMessageBox.prompt("专业名称", "创建专业", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^.+$/,
    inputErrorMessage: "未输入专业名称",
    inputPlaceholder: "输入专业名称",
  })
    .then(({ value }) => {
      addClass(value);
      ElMessage({
        type: "success",
        message: `添加了专业:${value}`,
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消创建专业",
      });
    });
};

// 修改班级名称
const update = (className, classId) => {
  ElMessageBox.prompt("专业名称", "修改专业", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    inputPattern: /^.+$/,
    inputErrorMessage: "未输入专业名称",
    inputPlaceholder: "输入专业名称",
    inputValue: className,
  })
    .then(async ({ value }) => {
      await updateClass(classId, value);
      getClassroomByTeacherId();
      ElMessage({
        type: "success",
        message: `修改了专业:${value}`,
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消修改",
      });
    });
};

// 搜索班级
const searchText = ref();
</script>

<style scoped lang="scss">
@import url(@/assets/font/iconfont.css);

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

a {
  text-decoration: none;
}

ul,
ol {
  list-style: none;
}

.resourceTop {
  width: 100%;
  height: 100px;
  background-color: white;
  border: 1px solid #f0f0f0;
  padding: 16px 60px;
}

.resourceTop .logo {
  width: 60px;
  height: 60px;
  background-color: #ff6b0f;
  border-radius: 50%;
  display: inline-block;
  justify-content: center;
  align-items: center;
}

.resourceTop .logo img {
  width: 60px;
  height: 60px;
  padding: 18px;
}

.resourceTop .text {
  width: 250px;
  height: 100%;
  margin-left: 20px;
  display: inline-block;
}

.resourceTop .text .title007 {
  font-size: 22px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 10px;
}

.resourceTop .text p span {
  color: rgba(0, 0, 0, 0.45);
}

.resourceTop .text p a {
  color: #f4523b;
}

.search {
  display: flex;
  float: right;
  border-radius: 2px;
  background-color: #fafafa;
  border: 1px solid #f0f0f0;
}

.sousuo {
  width: 40px;
  height: 40px;
  padding: 11px;
  background-color: #fff;
}

.resourceTop .search input {
  width: 320px;
  height: 40px;
  border: none;
  background-color: #fff;
}

.search input:focus {
  outline: none;
}

.search:hover {
  border: 1px solid #FF6B0F;
}

.nav-right {
  float: right;
  width: 95px;
  height: 100%;
  padding: 15px 0;
}

.button-zuzhang {
  float: right;
  width: 95px;
  height: 100%;
  padding: 15px 150px;
}

.subject-right-header {
  width: 100%;
}

.subject-right-body {

  background-color: #eeeeee;
  height: 78.5vh;
  width: 99.9%;
  padding: 24px 60px;
}

.table {
  height: 100px;
  width: 100%;
  // border: 1px solid red;
  z-index: 25;

}

::v-deep .el-table tr:hover {
  cursor: pointer;
}

.custom-margin {
  margin: 10px 0; // 自定义边距
}
</style>

